package com.lottery.system.service.impl;
import com.lottery.system.common.errorcode.ServiceErrorCodeConstants;
import com.lottery.system.common.exception.ServiceException;
import com.lottery.system.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: xiaoxie
 * create: 2024-09-06 15:17
 * @BelongsProject: lottery-system
 * @BelongsPackage: com.lottery.system.service.impl
 * description: 图片业务实现类
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private  String localPath;
    @Override
    public String savePicture(MultipartFile file) {
        //创建目录
        File dir = new File(localPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //创建索引
        String filename = file.getOriginalFilename();
        assert filename != null;
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID()+suffix;
        //图片保存
        try {
            file.transferTo(new File(localPath + "/" + filename));
        } catch (IOException e) {
            throw new ServiceException(ServiceErrorCodeConstants.PIC_UPLOAD_ERROR);
        }
        return filename;
    }
}
